package leetcode.editor.week.week315;

// 6207. 统计定界子数组的数目
// https://leetcode.cn/problems/count-subarrays-with-fixed-bounds/
public class Solution6207 {
    // https://leetcode.cn/problems/count-subarrays-with-fixed-bounds/solution/jian-ji-xie-fa-pythonjavacgo-by-endlessc-gag2/
    public long countSubarrays(int[] nums, int minK, int maxK) {
        int minL = -1, maxL = -1, i0 = -1, n = nums.length;
        long ans = 0;
        for (int i = 0; i < n; i++) {
            int val = nums[i];
            if (val == maxK) maxL = i;
            if (val == minK) minL = i;
            if (val < minK || val > maxK) i0 = i;
            ans += Math.max(Math.min(minL, maxL) - i0, 0);
        }

        return ans;
    }
}
